package com.mti.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mti.configuration.SystemConfig;
import com.mti.dao.dto.OrganizationDto;
import com.mti.service.CacheableService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Classname CacheableServiceImpl
 * @Description TODO
 * @Date 2020/2/8 16:15
 * @Created by duchaof
 * @Version 1.0
 */
@Slf4j
@Service
@CacheConfig(cacheNames = "RemoteDataCacheable")
public class CacheableServiceImpl implements CacheableService {

    @Autowired
    private SystemConfig systemConfig;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    @Cacheable(key = "#root.method+'('+#orgType+')'")
    public Map<String,String> getZrpcs(String orgType){
        ResponseEntity result = restTemplate.getForEntity(systemConfig.getSystemServer() +
                "/api/system/organization/getOrgByOrgtype?orgType="+orgType, JSONObject.class);
        Map<String,String> returnMap = new HashMap<>();
        if (null != result) {
            if (null != result.getBody()) {
                JSONObject obj = JSONObject.parseObject(result.getBody().toString());
                List<Map> res = JSONArray.parseArray(obj.get("data").toString(),Map.class);
                for(Map map : res){
                    returnMap.put((String) map.get("id"),(String) map.get("shortName"));
                }
            }
        }
        return returnMap;
    }

    @Override
    @Cacheable(key = "#root.method+'('+#shortName+')'+',('+#ssxqId+')'")
    public Map<String,Object> getOrganization(String shortName,String ssxqId){
        Map<String,Object> resultMap = null;
        try {
            Map<String,Object> paramMap = new HashMap<>();
            paramMap.put("shortName",shortName);
            paramMap.put("internal",1);
            if(null != ssxqId && ssxqId.length()>0){
               paramMap.put("regionPid",ssxqId);
            }
            JSONObject json = restTemplate.postForEntity(systemConfig.getSystemServer()
                    +"api/system/organization/list",paramMap,JSONObject.class).getBody();
            if(null != json){
                if (json.containsKey("data")) {
                    Map<String,Object> m = (Map<String, Object>) json.get("data");
                    List<Map<String,Object>> res = (List<Map<String,Object>>)m.get("records");
                    if(res.size()>0){
                        resultMap = res.get(0);
                    }
                }
            }
        } catch (RestClientException e) {
            log.error("查询分局或派出所是出现异常："+e.getMessage());
        }
        return resultMap;
    }

    @Override
    @Cacheable(key = "#root.method+'('+#mjxm+')'")
    public Map<String,Object> getZrmjInfo(String mjxm){
        Map<String, Object> returnMap = null;
        try {
            ResponseEntity result = restTemplate.getForEntity(systemConfig.getSystemServer()
                    + "/api/system/person/getByPerson?name="+mjxm, JSONObject.class);
            if(null != result){
                if (null != result.getBody()) {
                    JSONObject jsonObject = JSONObject.parseObject(result.getBody().toString());
                    if (jsonObject.containsKey("data")) {
                        returnMap  =  JSONObject.parseObject(jsonObject.get("data").toString(),Map.class);
                    }
                }
            }
        } catch (RestClientException e) {
            log.error("远程调用失败：====={}",e.getMessage());
        }
        return returnMap;
    }

    /**
     * 查询管控责任分局 和 责任派出所
     *
     * @param orgType
     * @return
     */
    @Override
    @Cacheable(key = "#root.method+'('+#orgType+')'")
    public List<String> getAllGkzrfj(String orgType) {
        ResponseEntity result = restTemplate.getForEntity(systemConfig.getSystemServer() +
                "/api/system/organization/getOrgByOrgtype?orgType=" + orgType, JSONObject.class);
        List<String> returnResult = new ArrayList<>();
        if (null != result) {
            if (null != result.getBody()) {
                JSONObject obj = JSONObject.parseObject(result.getBody().toString());
                List<Map> res = JSONArray.parseArray(obj.get("data").toString(), Map.class);
                for (Map map : res) {
                    returnResult.add((String) map.get("shortName"));
                }

            }
        }
        return returnResult;
    }

    /**
     * 查询区域 省：1；市：2；县：3；
     *
     * @param level
     * @return
     */

    @Override
    @Cacheable(key = "#root.method+'('+#level+')'")
    public List<String> getRegionByLevel(Integer level) {
        ResponseEntity result = restTemplate.getForEntity(systemConfig.getSystemServer() +
                "/api/system/region/getRegionByType?level=" + level, JSONObject.class);
        if (null != result) {
            if (null != result.getBody()) {
                JSONObject obj = JSONObject.parseObject(result.getBody().toString());
                List<String> res = JSONArray.parseArray(obj.get("data").toString(), String.class);
                return res;
            }
        }
        return null;
    }

    @Cacheable(key = "#root.method+'('+#arg+')'")
    @Override
	public Map<String, String> getAllRegionInfo(String arg) {
		Map<String, String> returnMap = null;
		try {
			ResponseEntity result = restTemplate.getForEntity(
					systemConfig.getSystemServer() + "api/system/region/getAllRegionInfo", JSONObject.class);
			returnMap = new HashMap<>();
			if (null != result) {
				if (null != result.getBody()) {
					JSONObject jsonObject = JSONObject.parseObject(result.getBody().toString());
					if (jsonObject.containsKey("data")) {
						List<Map> regiones = JSONArray.parseArray(jsonObject.get("data").toString(), Map.class);
						for (Map map : regiones) {
							returnMap.put((String) map.get("id"), (String) map.get("regionName"));
						}
					}
				}
			}
		} catch (RestClientException e) {
			e.getMessage();
		}
		return returnMap;
	}

    //@Cacheable(key = "#root.method+'('+#regionId+')'")
    @Override
   public List<OrganizationDto> getUpOrgById(String regionId){
        List<OrganizationDto> regiones = null;
        try {
            ResponseEntity result = restTemplate.getForEntity(
                    systemConfig.getSystemServer() + "api/system/organization/getAllUpOrganization?id="+regionId, JSONObject.class);
            if (null != result) {
                if (null != result.getBody()) {
                    JSONObject jsonObject = JSONObject.parseObject(result.getBody().toString());
                    if (jsonObject.containsKey("data")) {
                         regiones = JSONArray.parseArray(jsonObject.get("data").toString(), OrganizationDto.class);
                    }
                }
            }
        } catch (Exception e) {
            log.error("查询上级机构时发生异常：======》{}",e.getMessage());
        }

       return regiones;
   }



    @CacheEvict(allEntries = true)
    public void deleteAllCacheale(){
        System.out.println("删除所有的缓存");
    }
}
